$(document).ready(function () {
    updateRolesCombo();
    updateUsersCombo();

    $("#AddToRoleBtn").click(function () {
        var strUser = $("#UserSelect").val();
        var strRole = $("#RolesSelect").val();
        var inData = { "strUser": strUser, "strRole": strRole };
        $.post("/User/WSAddUserToRole/", inData, function (data) {
            updateRolesCombo();
            updateUsersCombo();
        });
    });


});


function removeFromRole(strUsrId, strRoleName) {
    inData = { "strUser": strUsrId, "strRole": strRoleName };
    $.post("/User/WSRemoveUserFromRole/", inData, function (data) {
        updateRolesCombo();
        updateUsersCombo();
    });
};

function updateUsersInRoles(roleName) {
    $.ajax(
    {
        type: "GET",
        contentType: "application/json; charset=iso8859-1",
        url: "/User/WSGetUsersInRole/",
        data: { "strRole": roleName },
        dataType: "json",
        success: function (data) {
            newRoleName = "#" + roleName;
            $(newRoleName).empty();
            $(UsersInRolesTemplate).tmpl(data).hide().appendTo(newRoleName).fadeIn("slow");
        },
        error: function (xhr, err) {
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
        }
    });
};


function updateUsersCombo() {
    $.ajax(
    {
        type: "GET",
        contentType: "application/json; charset=iso8859-1",
        url: "/User/WSGetUsers/",
        data: {},
        dataType: "json",
        success: function (data) {
            $("#UserSelect").empty();
            $("#UserOptionTemplate").tmpl(data).hide().appendTo("#UserSelect").fadeIn("slow");
        },
        error: function (xhr, err) {
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
        }
    });
};

function updateRolesCombo() {
    $.ajax(
    {
        type: "GET",
        contentType: "application/json; charset=iso8859-1",
        url: "/User/WSGetAllRoles/",
        data: {},
        dataType: "json",
        success: function (data) {
            $("#RolesSelect").empty();
            $("#RolesOptionTemplate").tmpl(data).hide().appendTo("#RolesSelect").fadeIn("slow");
            $("#ListUsersInRoles").empty();
            $("#RolesTemplate").tmpl(data).hide().appendTo("#ListUsersInRoles").fadeIn("slow");
            $.each(data, function () {
                $.each(this, function (i, value) {
                    updateUsersInRoles(value);
                });
            });
        },
        error: function (xhr, err) {
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
        }
    });
};